package com.itheima.mm.wx.controller;

import com.alibaba.fastjson.JSONObject;
import com.itheima.mm.constant.JwtClaimsConstant;
import com.itheima.mm.context.WxBaseContext;
import com.itheima.mm.dto.WxMemberLoginDTO;
import com.itheima.mm.entity.Result;
import com.itheima.mm.pojo.WxMember;
import com.itheima.mm.properties.JwtProperties;
import com.itheima.mm.utils.JwtUtil;
import com.itheima.mm.utils.WxUtil;
import com.itheima.mm.utils.DateUtils;
import com.itheima.mm.vo.wx.WxMemberVO;
import com.itheima.mm.wx.service.WxMemberService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;


/**
 * @Description WxMemberController
 * @Author junyi
 * @Date 2024-06-27
 */

@RestController
@Slf4j
//@RequestMapping("/user")
public class WxMemberController {

    @Autowired
    private WxMemberService wxMemberService;

    @Autowired
    private JwtProperties jwtProperties;


    /**
     *
     * @param wxMemberLoginDTO
     * @return
     * @throws Exception
     */
    //@PostMapping("/login.do")
    @PostMapping("/user/login")
    public WxMemberVO login(@RequestBody WxMemberLoginDTO wxMemberLoginDTO) throws Exception {

        //获取微信用户信息
        JSONObject wx = WxUtil.get(wxMemberLoginDTO.getCode());
        String sessionKey = wx.getString("session_key");
        String openId = wx.getString("openid");

        //查询微信用户表,存在就直接返回微信用户信息，不存在就新增后再返回微信用户信息
        //Object o = wus.dtl(openId);
        log.debug("openId:{},mapData:{}", openId, wxMemberLoginDTO);

        //openId = "oiu565SzoTCXctUD0y6Ll-RQOkFg";
        WxMember wxUser = wxMemberService.findByOpenId(openId);
        if (wxUser == null) {
            log.debug("注册会员....");

            //解析微信用户信息封装到wxUser对象中
            JSONObject userJson = WxUtil.getUserInfo(wxMemberLoginDTO.getEncryptedData(), sessionKey, wxMemberLoginDTO.getIv());
            wxUser = new WxMember();
//            wxUser.setNickName(userJson.getString("nickName"));
//            wxUser.setAvatarUrl(userJson.getString("avatarUrl"));
//            wxUser.setGender(userJson.getString("gender"));
//            wxUser.setCity(userJson.getString("city"));
//            wxUser.setProvince(userJson.getString("province"));
//            wxUser.setLanguage(userJson.getString("language"));
            wxUser.setOpenId(openId);
//            wxUser.setOpenId(userJson.getString("openId"));
////            wxUser.setUnionId(userJson.getString("unionId"));
////            //wxUser.setCreateTime(userJson.getString("createTime"));
            wxUser.setCreateTime(DateUtils.parseDate2String(new Date()));

            //调用服务，执行新增操作
            wxMemberService.add(wxUser);
        }
//        } else {
//
//            log.debug("登录会员");
//        }

        //返回微信用户信息openId
        String wxUid = wxUser.getOpenId();

        //登录成功后，生成jwt令牌
        Map<String, Object> claims = new HashMap<>();
        claims.put(JwtClaimsConstant.WX_USER_ID, wxUser.getId());
        claims.put("openId", wxUid);
        String token = JwtUtil.createJWT(jwtProperties.getUserSecretKey(), jwtProperties.getUserTtl(), claims);

        //创建并返回WxMemberVO数据
        WxMemberVO wxMemberVO = new WxMemberVO();
        wxMemberVO.setToken(token);
        wxMemberVO.setUserInfo(wxUser);

        return wxMemberVO;
    }

    /**
     * 更新用户城市及科学方向
     * @param mapData
     * @return
     * @throws Exception
     */
    @PostMapping("/member/setCityCourse.do")
    public Result<WxMemberVO> setCityCourse(@RequestBody Map<String, String> mapData) throws Exception {
        String openId = WxBaseContext.getCurrentId();
        mapData.put("openId", openId);
        log.debug("mapData", mapData);
        wxMemberService.updateCityCourse(mapData);
        return Result.success(null, "更新成功");
    }
}
